<template>
    <div>
        <TableSearch :query="query" :options="searchOpt" :search="handleSearch" />
        <div class="container">
            <TableCustom :columns="columns" :tableData="tableData" :total="page.total" row-key="o_order_code"
            :changePage="changePage" :currentPage="page.page" :pageSize="page.page_size" :change-page-size="changePageSize">
                <template #o_is_refund="{rows}">
                    <el-tag v-if="rows.o_is_refund == -1" type="success">已退款</el-tag>
                    <el-tag v-else-if="rows.o_is_refund == 1" type="warning">退款中</el-tag>
                    <el-tag v-else-if="rows.o_is_refund == 0" type="danger">未退款</el-tag>
                </template>
                <template #o_status="{rows}">
                    <el-tag v-if="rows.o_status == 3" type="success">已还镜</el-tag>
                    <el-tag v-else-if="rows.o_status == 2" type="danger">未归还</el-tag>
                    <el-tag v-else-if="rows.o_status == 4" type="warning">部分还镜</el-tag>
                </template>
                <template #operator="{rows}">
                    <!-- :disabled="(rows.o_glasses_num - rows.num) == 0" -->
                    <el-button :disabled="rows.o_is_refund == -1 || rows.o_is_refund == 1" :loading="rows.o_is_refund == 1" type="warning" @click="backMoney(rows)" >{{rows.o_is_refund == 1 ? '退款中' : rows.o_is_refund == 0 ? '退款' : '已退款'}}</el-button>
                </template>
                <template #glasses_data="{rows}">
                    <el-table style="width: 80%; margin: 20px 5% 20px;" :data="rows.glasses_data" border>
                        <template v-for="oItem in ChildrenColumns" :key="oItem.prop" >
                            <el-table-column :prop="oItem.prop" :label="oItem.label" :align="'center'">
                                <template #default="props">
                                    <slot :name="oItem.prop" :rows="props.row[oItem.prop]" :key="props.row.$index">
                                        <span v-if="oItem.prop == 'go_status'">
                                            <el-tag v-if="props.row.go_status == 1" type="success">已归还</el-tag>
                                            <el-tag v-else-if="props.row.go_status == -1" type="danger">未归还</el-tag>
                                        </span>
                                        <span v-else>
                                            {{ props.row[oItem.prop] }}
                                        </span>
                                    </slot>
                                </template>
                            </el-table-column>
                        </template>
                    </el-table>
                </template>
                <template #o_order_code="{rows}">
                    <el-button type="primary" link @click="gotoDetail(rows)">{{rows.o_order_code}}</el-button>
                </template>
            </TableCustom>
            <el-dialog
                v-model="dialogVisible"
                title="退款操作"
                width="500"
            >
                <el-form
                    ref="ruleFormRef"
                    style="max-width: 600px"
                    :model="ruleForm"
                    :rules="rules"
                    label-width="auto"
                    :size="formSize"
                    status-icon
                >
                    <el-form-item label="退款原因" prop="refund_reason">
                        <el-input type="textarea" v-model="ruleForm.refund_reason" />
                    </el-form-item>
                    <el-form-item label="眼镜数量" prop="refund_num">
                        <el-input-number v-model="ruleForm.refund_num" :min="0" :max="MaxNum"/>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                        <el-button type="primary" @click="conformBackMoney(ruleFormRef)">确认</el-button>
                        </el-form-item>
                    </el-form>
            </el-dialog>
        </div>
    </div>
</template>

<script setup lang="ts" name="collaborativeAdministrator-user">
import { ref, reactive, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { CirclePlusFilled, Loading } from '@element-plus/icons-vue';
import { return_order_glasses, hand_refund } from '@/api';
import TableCustom from '@/components/table-custom.vue';
import TableSearch from '@/components/table-search.vue';
import { FormOption, FormOptionList } from '@/types/form-option';
import { useRouter } from 'vue-router';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

const getNowTime = () => {
    return `${new Date().getFullYear()}-${(new Date().getMonth() + 1) > 9 ? (new Date().getMonth() + 1) : '0' + (new Date().getMonth() + 1)}-${new Date().getDate() > 9 ? new Date().getDate() : '0' + new Date().getDate()}`
}

// 查询相关
const query = reactive({
    data_time: [getNowTime(), getNowTime()],
    o_order_code: null,
    user_telphone: null,
    refund_status:null,
    glasses_status: null
});
// 查询条件相关
const searchOpt = ref<FormOptionList[]>([
    // { type: 'select', label: '审核状态：', prop: 'g_type', placeholder: '请选择审核状态'},
    { type: 'daterange', label: '查询时间：', prop: 'data_time', placeholder: '请选择时间范围', format: 'YYYY-MM-DD'},
    { type: 'select', label: '眼睛借还状态：', prop: 'glasses_status', placeholder: '请选择眼睛借还状态', opts: [{value: 1, label: "待取境"},  {value: 2, label: "待还镜"}]},
    { type: 'select', label: '押金退还状态：', prop: 'refund_status', placeholder: '请选择押金退还状态', opts: [{value: 1, label: "已退还"},  {value: -1, label: "未退还"}]},
    { type: 'input', label: '订单编号：', prop: 'o_order_code', placeholder: '请输入订单编号' },
    { type: 'input', label: '租户手机号：', prop: 'user_telphone', placeholder: '请输入租户手机号' },
    // { type: 'select', label: '退还状态：', prop: 'g_type', placeholder: '请选择退还状态'},
])
const handleSearch = () => {
    if (!query.user_telphone) query.user_telphone = null
    changePage(1);
};

// 表格相关
let columns = ref([
    // {type: 'selection'},
    { prop: 'glasses_data', label: '', type: 'expand'},
    { prop: 'o_order_code', label: '订单编号', },
    { prop: 'user_telphone', label: '租户名称', width: 90 },
    { prop: 'o_glasses_num', label: '眼镜数量', width: 90 },
    { prop: 'f_num', label: '已还镜数量', width: 140 },
    { prop: 'o_money', label: '押金', width: 90 },
    { prop: 'o_start_time', label: '订单时间', width: 200 },
    // { prop: 'o_pay_time', label: '支付时间' },
    { prop: 'o_is_refund', label: '是否退款', width: 90 },
    { prop: 'o_status', label: '归还状态', width: 90 },
    // { prop: 'go_order_date', label: '还镜日期' },
    { prop: 'o_area', label: '归还区域', width: 120 },
    { prop: 'operator', label: '操作', width: 150 },
])
// 嵌套表格数据
const ChildrenColumns = [
        { prop: 'glasses_type', label: '眼镜类型' },
        { prop: 'go_code', label: '眼镜编码' },
        { prop: 'go_output_time', label: '借出时间' },
        { prop: 'go_input_time', label: '归还时间' },
        { prop: 'go_status', label: '借还状态' },
    ]
const page = reactive({
    page: 1,
    page_size: 10,
    total: 0,
})
// 押金返还

const MaxNum = ref(1)
interface RuleForm {
    o_order_code: string,
    refund_num: number,
    refund_reason: string
}
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    o_order_code:'',
    refund_num: 0,
    refund_reason: '正常退款',
})
const rules = reactive<FormRules<RuleForm>>({
    refund_reason: [
        { required: true, message: '请输入退款原因', trigger: 'blur' },
    ],
    refund_num:[
        { required: true, message: '请输入退款的眼镜数量', trigger: 'change' },
    ],
})
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dialogVisible.value = false
}
const dialogVisible = ref(false)
const tempObj = ref({o_is_refund: 0})
const backMoney = (data) => {
    tempObj.value = data
    ruleForm.refund_num = Number(data.num - data.f_num)
    ruleForm.o_order_code = data.o_order_code
    ruleForm.refund_reason = '正常退款'
    MaxNum.value = Number(data.num - data.f_num)
    dialogVisible.value = true
}

const conformBackMoney = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
           ElMessageBox.confirm('确认要退款？', '提示').then(() => {
                hand_refund({...ruleForm}).then(res => {
                    if(res.code == '1000') {
                        ElMessage({
                            type: 'success',
                            message: '退款申请成功',
                        })
                        tempObj.value.o_is_refund = 1
                        resetForm(formEl)
                    } else {
                        ElMessage({
                            type: 'error',
                            message: res.msg,
                        })
                    }
                    
                })
            }).catch(() => {
                ElMessage({
                    type: 'info',
                    message: '取消退款',
                })
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const tableData = ref<[]>([]);
const getData = async () => {
    const res = await return_order_glasses({page: page.page, page_size: page.page_size, ...query})
    tableData.value = res.data.data_list;
    page.total = res.data.total;
};
getData();
const changePage = (val: number) => {
    // console.log(val)
    page.page = val;
    getData();
};
const changePageSize = (val: number) => {
    page.page_size = val;
    getData();
};

// 新增/编辑弹窗相关
let options = ref<FormOption>({
    labelWidth: '150px',
    span: 20,
    list: [
        { type: 'select', label: '眼镜分类', prop: 'g_type', required: true, placeholder: '请选择眼镜类别' },
        { type: 'textarea', label: '芯片序列号', prop: 'glasses_data', required: true, placeholder: '请输入芯片序列号' },
    ]
})
const router = useRouter();
//  跳转详情
const gotoDetail = (row) => {
    router.push({
        name: 'galssOrder-orderInfoDetail',
        query: {o_order_code: row.o_order_code},
    })
}


// 删除相关
const handleDelete = (row) => {
    ElMessageBox.confirm('审核该订单', '提示', {
        type: 'warning'
    })
        .then(async () => {
        })
        .catch(() => { });
    
}
</script>

<style scoped></style>